"use client"

import { useEffect, useState, ReactNode} from "react"
import { usePathname, useRouter } from "next/navigation"
import { Home, MessageCircle, User, Moon, Sun, LogOut, PanelLeft} from "lucide-react"
import { useTheme } from "next-themes"

import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarTrigger,
  useSidebar
} from "@/components/ui/sidebar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import router from "next/router"

const API_URL = 'http://127.0.0.1:8000'
interface UserInfo {
  id: number;
  name: string;
  account_id?: string; // 用户账号ID
  role: string;
  student?: {
    academy: string;  // 学院
    major: string;    // 专业
    class_: string;   // 班级 
  };
  counselor?: {
    department: string; // 部门
  };
}

async function fetchCurrentUser(): Promise<UserInfo | null> {
  try {
    const response = await fetch(`${API_URL}/api/v1/auth/login`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      if (response.status === 401) {
        console.error('认证失败，可能需要重新登录');
        // 可选：重定向到登录页
        return null;
      }
      throw new Error(`API错误: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('获取用户数据失败:', error);
    return null;
  }
}

interface DashboardSidebarProps {
  children?: ReactNode;
}

export function DashboardSidebar({ children }: DashboardSidebarProps) {
  const router = useRouter()
  const pathname = usePathname()
  const { state, toggleSidebar } = useSidebar()

  const isActive = (path: string) => pathname === path
  const [userName, setUserName] = useState("加载中...");
  const [academyId, setAcademyId] = useState("加载中...");


  return (
    <Sidebar collapsible="icon">
      <SidebarHeader className="border-t">
        <div className="flex flex-col gap-5 pl-2">
          <div className="font-semibold text-lg flex justify-between items-center">
            {state === "expanded" ? (
              <span>AI辅导员</span>
            ) : (
              <span>AI</span>
            )}
            {state === "expanded" && (
              <Button variant="ghost" size="icon" onClick={toggleSidebar}>
                <PanelLeft className="h-5 w-5" />
                <span className="sr-only">切换菜单</span>
              </Button>
            )}
          </div>
        </div>
      </SidebarHeader>
      
      <SidebarContent>
        <SidebarGroup>
          <SidebarGroupLabel className={state === "collapsed" ? "sr-only" : ""}>导航</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton 
                  asChild
                  className={isActive("/dashboard") ? "bg-sidebar-accent" : ""}
                  onClick={() => router.push("/dashboard")}
                >
                  <div className="flex items-center">
                    <Home className="h-5 w-5 flex-shrink-0" />
                    <span className={state === "collapsed" ? "sr-only" : "ml-2"}>主页</span>
                  </div>
                </SidebarMenuButton>
              </SidebarMenuItem>
              <SidebarMenuItem>
                <SidebarMenuButton 
                  asChild
                  className={isActive("/dashboard/ai-assistant") ? "bg-sidebar-accent" : ""}
                  onClick={() => {
                    router.push("/dashboard/ai-assistant");
                    if (state === "expanded") {
                      toggleSidebar();
                    }
                  }}
                >
                  <div className="flex items-center">
                    <MessageCircle className="h-5 w-5 flex-shrink-0" />
                    <span className={state === "collapsed" ? "sr-only" : "ml-2"}>咨询AI辅导员</span>
                  </div>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
        
        <SidebarGroup>
          <SidebarGroupLabel className={state === "collapsed" ? "sr-only" : ""}>用户</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton 
                  asChild
                  className={isActive("/dashboard/profile") ? "bg-sidebar-accent" : ""}
                  onClick={() => router.push("/dashboard/profile")}
                >
                  <div className="flex items-center">
                    <User className="h-5 w-5 flex-shrink-0" />
                    <span className={state === "collapsed" ? "sr-only" : "ml-2"}>个人信息</span>
                  </div>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>
      
      {/* 折叠菜单按钮 - 仅在折叠状态下显示 */}
      {state === "collapsed" && (
        <div className="flex justify-center p-2 mb-2">
          <Button variant="ghost" size="icon" onClick={toggleSidebar} className="h-10 w-10">
            <PanelLeft className="h-5 w-5" />
            <span className="sr-only">展开菜单</span>
          </Button>
        </div>
      )}
      
      <SidebarFooter className="border-t">
        {state === "expanded" ? (
            <SidebarMenu className="mt-2">
              <SidebarMenuItem>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <SidebarMenuButton className="w-full justify-between">
                      <div className="flex items-center">
                        <div className="h-6 w-6 rounded bg-gradient-to-br from-indigo-500 to-cyan-400 mr-2" />
                        <div>
                          {/*<span className="text-sm font-medium">{userName}</span>*/}
                          {/*<div className="text-xs text-muted-foreground">{academyId}</div>*/}
                        </div>
                      </div>
                      <div className="ml-auto">
                        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className="ml-auto h-4 w-4 opacity-50">
                          <path d="M2.5 7.5L6 4L9.5 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                        </svg>
                      </div>
                    </SidebarMenuButton>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="start" className="w-56">
                    <DropdownMenuItem onClick={() => router.push("/login")}>
                      <LogOut className="mr-2 h-4 w-4" />
                      <span>退出登录</span>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </SidebarMenuItem>
            </SidebarMenu>
        ) : (
          <div className="flex justify-center p-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="h-8 w-8">
                  <div className="h-6 w-6 rounded bg-gradient-to-br from-indigo-500 to-cyan-400" />
                  <span className="sr-only">用户菜单</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <div className="px-2 py-1.5 flex flex-col">
                  {/*<span className="font-medium">{userName}</span>*/}
                  {/*<span className="text-xs text-muted-foreground">{academyId}</span>*/}
                </div>
                <Separator className="my-1" />
                
                <DropdownMenuItem onClick={() => router.push("/login")}>
                  <LogOut className="mr-2 h-4 w-4" />
                  <span>退出登录</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        )}
      </SidebarFooter>
    </Sidebar>
  )
} 